import request from './request'

// 分类列表查询
export const getCategoryList = (params) => {
  return request.get('/category/list', { params })
}

// 分类详情查询
export const getCategoryDetail = (id) => {
  return request.get(`/category/${id}`)
}

// 分类新增
export const createCategory = (categoryData) => {
  return request.post('/category', categoryData)
}

// 分类更新
export const updateCategory = (categoryData) => {
  return request.put('/category', categoryData)
}

// 分类删除
export const deleteCategory = (id) => {
  return request.delete(`/category/${id}`)
}

// 获取顶级分类
export const getTopCategories = () => {
  return getCategoryList({ parentId: 0 })
}

// 获取子分类
export const getSubCategories = (parentId) => {
  return getCategoryList({ parentId })
}

// 构建分类树形结构的工具函数
export const buildCategoryTree = (categories) => {
  const map = {}
  const tree = []
  
  // 先建立id映射
  categories.forEach(category => {
    map[category.id] = { ...category, children: [] }
  })
  
  // 构建树形结构
  categories.forEach(category => {
    if (category.parentId === 0) {
      tree.push(map[category.id])
    } else if (map[category.parentId]) {
      map[category.parentId].children.push(map[category.id])
    }
  })
  
  return tree
}
